from django import template
from django import forms
from django.http import HttpResponseRedirect
from genericview.views import HttpRedirectException
from pirateissues.models import Issue

register = template.Library()

@register.tag("pirate-issue-form")
def do_issue_form_tag(parser, token):
    nodelist = parser.parse(('end-issue-form',))
    parser.delete_first_token()
    return GetIssueFormNode(nodelist)

class GetIssueFormNode(template.Node):
    def __init__(self, nodelist):
        self._nodelist = nodelist

    def render(self, context):
        if 'request' not in context or 'path' not in context or 'topic' not in context:
            raise ValueError("This tag requires three specific argments to be supplied: " +
                                 "'request' of type HTTPRequest, 'path' of type string, and 'topic' of type int")

        request = context['request']
        path    = context['path']

        if 'pirate_issues' in context:
            pirate_issues = context['pirate_issues'].copy()
        else:
            pirate_issues = {}

        if request.POST and request.POST.get("form_id") == "issue-form":
            form = IssueForm(request.POST)
            if form.is_valid():
                new_issue = form.save()
                raise HttpRedirectException(HttpResponseRedirect("/" + path))
        else:
            form = IssueForm()

        pirate_issues['form'] = form

        context.push()
        context['pirate_issues'] = pirate_issues 
        output = self._nodelist.render(context)
        context.pop()

        return output


class IssueForm(forms.ModelForm):
    class Meta:
        model = Issue

    form_id = forms.CharField(widget=forms.HiddenInput(), initial="issue-form")


